package com.suray.wcs.web.system.controller;

import com.suray.commin.annotation.Log;
import com.suray.commin.config.WCSConfig;
import com.suray.commin.core.controller.BaseController;
import com.suray.commin.core.controller.ResponseData;
import com.suray.commin.core.page.TableDataInfo;
import com.suray.commin.core.utils.*;
import com.suray.commin.enmus.BusinessType;
import com.suray.commin.core.utils.SecurityUtils;
import com.suray.commin.core.pojo.LoginBO;
import com.suray.commin.core.pojo.LoginUser;
import com.suray.wcs.service.system.entity.MenuDB;
import com.suray.commin.core.entity.RoleDB;
import com.suray.commin.core.entity.UserDB;
import com.suray.wcs.service.system.service.IRoleDBService;
import com.suray.wcs.service.system.service.IUserDBService;
import com.suray.wcs.service.system.service.impl.MenuDBServiceImpl;
import com.suray.wcs.service.system.service.impl.SysPermissionService;
import com.suray.wcs.service.system.service.impl.TokenService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserDBController extends BaseController {

    @Autowired
    private IUserDBService IUserDBService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private MenuDBServiceImpl menuDBService;

    @Autowired
    private IRoleDBService roleService;


    /**
     * 登陆
     *
     * @param loginBO
     * @author zhanghr
     */
    @Log(title = "用户管理", method = "登录", businessType = BusinessType.UPDATE)
    @ApiOperation("登录")
    @PostMapping("/login")
    public ResponseData login(@RequestBody LoginBO loginBO) {
        ResponseData responseData = ResponseData.success();
        // 生成令牌
        String token = IUserDBService.login(loginBO.getUsername(), loginBO.getPassword(), loginBO.getCode(),
                loginBO.getUuid());
        responseData.put(Constants.TOKEN, token);
        return responseData;
    }

    /**
     * 登出
     *
     * @author zhanghr
     */
    @Log(title = "用户管理", method = "退出", businessType = BusinessType.UPDATE)
    @ApiOperation("退出")
    @PostMapping("/logout")
    @CrossOrigin(value = "*", allowCredentials = "true")
    public ResponseData logout() {
        return ResponseData.error(HttpStatus.SUCCESS, "退出成功");
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/getInfo")
    public ResponseData getInfo() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserDB user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        ResponseData responseData = ResponseData.success();
        responseData.put("user", user);
        responseData.put("roles", roles);
        responseData.put("permissions", permissions);
        return responseData;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation("获取路由信息")
    @GetMapping("getRouters")
    public ResponseData getRouters() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        UserDB user = loginUser.getUser();
        List<MenuDB> menus = menuDBService.selectMenuTreeByUserId(user.getUserId());
        return ResponseData.success(menuDBService.buildMenus(menus));
    }


    /**
     * 获取用户列表
     */
    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('user:list')")
    @GetMapping("/list")
    public TableDataInfo list(UserDB user) {
        startPage();
        List<UserDB> list = IUserDBService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("根据用户编号获取详细信息")
    @GetMapping(value = {"/", "/{userId}"})
    public ResponseData getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        ResponseData responseData = ResponseData.success();
        List<RoleDB> roles = roleService.selectRoleAll();
        responseData.put("roles", UserDB.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId)) {
            responseData.put(ResponseData.DATA_TAG, IUserDBService.getByUserId(userId.toString()));
            responseData.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return responseData;
    }

    /**
     * 新增用户
     */
    @ApiOperation("新增用户")
    @PreAuthorize("@ss.hasPermi('user:add')")
    @Log(title = "用户管理", method = "新增用户", businessType = BusinessType.INSERT)
    @PostMapping
    public ResponseData add(@Validated @RequestBody UserDB user) {
        if (UserConstants.NOT_UNIQUE.equals(IUserDBService.checkUserNameUnique(user.getUserName()))) {
            return ResponseData.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(IUserDBService.checkPhoneUnique(user))) {
            return ResponseData.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(IUserDBService.checkEmailUnique(user))) {
            return ResponseData.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(IUserDBService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @PreAuthorize("@ss.hasPermi('user:edit')")
    @Log(title = "用户管理", method = "修改用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResponseData edit(@Validated @RequestBody UserDB user) {
        IUserDBService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(IUserDBService.checkPhoneUnique(user))) {
            return ResponseData.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(IUserDBService.checkEmailUnique(user))) {
            return ResponseData.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(IUserDBService.updateUser(user));
    }

    /**
     * 状态修改
     */
    @ApiOperation("状态修改")
    @PreAuthorize("@ss.hasPermi('user:edit')")
    @Log(title = "用户管理", method = "状态修改", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResponseData changeStatus(@RequestBody UserDB user) {
        IUserDBService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(IUserDBService.updateUserStatus(user));
    }

    /**
     * 删除用户
     */
    @ApiOperation("删除用户")
    @PreAuthorize("@ss.hasPermi('user:remove')")
    @Log(title = "用户管理", method = "删除用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public ResponseData remove(@PathVariable Long[] userIds) {
        return toAjax(IUserDBService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @PreAuthorize("@ss.hasPermi('user:resetPwd')")
    @Log(title = "用户管理", method = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public ResponseData resetPwd(@RequestBody UserDB user) {
        IUserDBService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(IUserDBService.resetPwd(user));
    }

    @ApiOperation("导出用户")
    @Log(title = "用户管理", method = "导出用户", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('user:export')")
    @GetMapping("/export")
    public ResponseData export(UserDB user) {
        List<UserDB> list = IUserDBService.selectUserList(user);
        ExcelUtil<UserDB> util = new ExcelUtil<UserDB>(UserDB.class);
        return util.exportExcel(list, "用户数据");
    }

    /**
     * 导入用户
     *
     * @param file
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @ApiOperation("导入用户")
    @Log(title = "用户管理", method = "导入用户", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public ResponseData importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<UserDB> util = new ExcelUtil<UserDB>(UserDB.class);
        List<UserDB> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = IUserDBService.importUser(userList, updateSupport, operName);
        return ResponseData.success(message);
    }

    /**
     * 导出模板
     *
     * @return
     */
    @ApiOperation("导出模板")
    @GetMapping("/importTemplate")
    public ResponseData importTemplate() {
        ExcelUtil<UserDB> util = new ExcelUtil<UserDB>(UserDB.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 个人信息
     */
    @ApiOperation("个人信息")
    @GetMapping("/profile")
    public ResponseData profile() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        UserDB user = loginUser.getUser();
        ResponseData ajax = ResponseData.success(user);
        ajax.put("roleGroup", IUserDBService.selectUserRoleGroup(loginUser.getUsername()));
        return ajax;
    }

    /**
     * 修改用户
     */
    @ApiOperation("修改用户")
    @Log(title = "个人信息", method = "修改用户", businessType = BusinessType.UPDATE)
    @PutMapping("/profile")
    public ResponseData updateProfile(@RequestBody UserDB user)
    {
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(IUserDBService.checkPhoneUnique(user)))
        {
            return ResponseData.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(IUserDBService.checkEmailUnique(user)))
        {
            return ResponseData.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        if (IUserDBService.updateUserProfile(user) > 0)
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            return ResponseData.success();
        }
        return ResponseData.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @ApiOperation("重置密码")
    @Log(title = "个人信息", method = "重置密码", businessType = BusinessType.UPDATE)
    @PutMapping("/profile/updatePwd")
    public ResponseData updatePwd(String oldPassword, String newPassword)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password))
        {
            return ResponseData.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password))
        {
            return ResponseData.error("新密码不能与旧密码相同");
        }
        if (IUserDBService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword)) > 0)
        {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return ResponseData.success();
        }
        return ResponseData.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @ApiOperation("头像上传")
    @Log(title = "用户头像", method = "头像上传", businessType = BusinessType.UPDATE)
    @PostMapping("/profile/avatar")
    public ResponseData avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(WCSConfig.getAvatarPath(), file);
            if (IUserDBService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                ResponseData ajax = ResponseData.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return ResponseData.error("上传图片异常，请联系管理员");
    }
}
